package org.consoleTesting;

import java.util.List;
import java.util.Scanner;

import org.testing.model.InOutManager;
import org.testing.model.AuthSystem;
import org.testing.model.Session;
import org.testing.model.Test;
import org.testing.model.UserFileStatistics;
import org.testing.model.results.Result;

public class ConsoleTesting implements OnUserMenuKeyListener {
	private static final int QUESTIONS_FOR_TEST = 10;
	private static Session session;

	public static void main(String[] args) {
		ConsoleTesting testingApp = new ConsoleTesting();
		testingApp.run();			
	}

	private void run() {
		ProgramMenu menu = new ProgramMenu();
		menu.setOnUserMenuKeyListener(this);
		session = new Session();
		session.setCommonUser(menu.login());
		menu.mainMenu();
	}
	
	@Override
	public void OnChooseItem(ItemSelectEvent event) {
		switch (event.getSelectedItem()) {
		case ProgramMenu.STATISTICS_ENTRY:
			if (session.commonUserIsAdmin()) {
				showStatisticsForAdmin();
			} else {
				System.out.println(UserFileStatistics.getUserStatistic(session.commonUserName()));
			}
		case ProgramMenu.TEST_ENTRY:
			testProcessing();
			break;
		case ProgramMenu.LOGOUT_ENTRY:
			break;
		case ProgramMenu.EXIT_ENTRY:
			exit();
		}
	
		
	}

	private static void showStatisticsForAdmin() {
		System.out.println(AuthSystem.allUsersForDisplay());
		System.out.println("Choose user id to show its statistic\n");
		int userId = Integer.parseInt(new Scanner(System.in).nextLine());
		String userName = AuthSystem.getUserName(userId);
		System.out.println(UserFileStatistics.getUserStatistic(userName) + "\n");

	}

	private static void exit() {
		System.out.println("Have a nice day!");
		System.exit(0);
	}

	private static void testProcessing() {
		Test myPrivateTest = new Test(new InOutManager(System.in, System.out));
		QuestionsMaker teacher = new QuestionsMaker();
		myPrivateTest.loadQuestions(teacher
				.getQuestionsForTest(QUESTIONS_FOR_TEST));
		List<Result> testResults;
		if (myPrivateTest.isReadyToTest()) {
			testResults = myPrivateTest.conductTheTest();
			processResults(testResults);
			System.out.println();
		}
	}

	private static void processResults(List<Result> resultsOfTheTest) {
		double wholeResults = 0;
		for (Result commonResult : resultsOfTheTest) {
			wholeResults += commonResult.toDouble();
		}
		UserFileStatistics.writeStatistics(wholeResults, session.commonUserName(),QUESTIONS_FOR_TEST);
		printResultToPromt(wholeResults);
	}

	

	private static void printResultToPromt(double result) {
		System.out.printf("Your result is" + "\n" + result + " of "
				+ QUESTIONS_FOR_TEST + "\n");
	}

	
}
